import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
// import getters from './getters'
// import popup from '@/store/modules/popup.js' 
const delay = ms => new Promise((resolve, reject) => setTimeout(resolve, ms))

// const modules = {}
// const files = require.context('./modules', false, /\.js$/)
// files.keys().forEach(key => {
// 	modules[key.replace(/(modules|\/|\.|js)/g, '')] = {
// 		...files(key).default,
// 		namespaced: true,
// 	}
// })
import {
	setState
} from '@/store/lifeData'
import {
	getLoginInfo,
	oneKeyLogin,
	oneKeyLoginUnipush,
	loginLog
} from '../apis/login/index.js'



import {
	nurseAuthorizationLocating
} from '@/apis/order/index.js'
import {
	authentication
} from '../apis/index/index.js'
// import {
// 	selectAllUrgencyLinkman
// } from '../apis/security/index.js'
import dayjs from "@/plugin/dayjs/dayjs.min.js";
import {
	selectNurseInviteRemind
} from '../apis/invite/index.js'
// const modulesFiles = require.context('./modules', true, /\.js$/);
// const modules = modulesFiles.keys().reduce((modules, modulePath) => {
// 	const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
// 	const value = modulesFiles(modulePath)
// 	modules[moduleName] = value.default
// 	return modules
// }, {})

const lifeDataNamespace = 'lifeData'
const lifeData = uni.getStorageSync(lifeDataNamespace) || {}

const store = new Vuex.Store({
	namespaced: true,
	state: {
		lifeDataNamespace,
		saveStateKeys: [],
		uuid: uni.getStorageSync('uuid') || '', //手机设备唯一标识号
		token: uni.getStorageSync('token') || '', //token
		userInfo: uni.getStorageSync('userInfo') || '', //用户基本信息
		wxUserInfo: uni.getStorageSync('wxUserInfo') || '', //用户基本信息
		system: uni.getStorageSync('system') || '', //系统信息
		// 这个地址直接存储个字符串，截取吧要不然，这样好麻烦了一个一个存
		city: uni.getStorageSync('city') || '', //用户定位城市(首页使用)
		location: uni.getStorageSync('location') || '', //用户定位经纬度
		latitude: uni.getStorageSync('latitude') || '',
		longitude: uni.getStorageSync('longitude') || '',
		address: uni.getStorageSync('address') || '', //用户定位的详细地址具体到街道
		detailAddress: uni.getStorageSync('detailAddress') || '', //省市区地理位置
		attestStatus: uni.getStorageSync('attestStatus') || '', //是否完成职业资格认证
		nameStatus: uni.getStorageSync('nameStatus') || '', //是否实名认证
		contactList: uni.getStorageSync('contactList') || '', //紧急联系人
		contactLists: uni.getStorageSync('contactLists') || [],
		isLogin: uni.getStorageSync('isLogin') || '', //判断登录
		hasUncompleteOrder: uni.getStorageSync('hasUncompleteOrder') || true,
		curItem: uni.getStorageSync('curItem') || '',
		myaddress: uni.getStorageSync('myaddress') || '',
		hospitalAddress: uni.getStorageSync('hospitalAddress') || '', // 更新订单里的地址
		breathe: uni.getStorageSync('breathe') || '',
		animalHeat: uni.getStorageSync('animalHeat') || '',
		bloodPressure: uni.getStorageSync('bloodPressure') || '',
		sphygmus: uni.getStorageSync('sphygmus') || '',
		timer: uni.getStorageSync('timer') || '',
		launch: uni.getStorageSync('launch') || 1,
		isRecord: uni.getStorageSync('isRecord') || '',
		cid: '',
		startServeLocation: null,
		myInviteObj: uni.getStorageSync('myInviteObj') || null,
		// 首页是否展示邀请弹框
		showInvite: uni.getStorageSync('showInvite') || false,
		myAssrue: false,
		// 护理报告模版
		reportTemplate: [],
		Nurseid: null,
		lastReportTimestamp: 0, // 上次上报时间戳
		reportInterval: 60, // 上传间隔时间（秒）
	},
	// modules,
	getters: {


	},
	mutations: {
		setState,
		disableToLogin(state, status) {
			if (status == 2) {
				uni.navigateTo({
					url: '/pages/login-register/login/login'
				})
			}

		},
		setNurseid(state, id) {
			state.Nurseid = id;
		},
		setShowInvite(state, payload) {
			uni.setStorageSync('showInvite', payload)
			state.showInvite = payload
		},
		saveReportTemplate(state, payload) {
			state.reportTemplate = payload
		},
		setMyAssure(state, payload) {
			state.myAssrue = payload
		},
		setStartServeLocation(state, payload) {
			state.startServeLocation = payload
		},
		mycid(state, payload) {
			state.cid = payload
		},

		setCity(state, payload) {
			uni.setStorageSync('city', payload)
			state.city = payload
		},
		setLocation(state, payload) {
			uni.setStorageSync('location', payload)
			state.location = payload
		},
		setLatitude(state, payload) {
			console.log('修改一次经纬度，------------------------------------------------')
			uni.setStorageSync('latitude', payload)
			state.latitude = payload
		},
		setLongitude(state, payload) {
			uni.setStorageSync('longitude', payload)
			state.longitude = payload
		},
		setAddress(state, payload) {
			uni.setStorageSync('address', payload)
			state.address = payload
			console.log(payload, 'aaaaaaaaaaaaaaaddddddddddddddrrrrrrrrresss')
		},
		setAnimalHeat(state, payload) {
			uni.setStorageSync('animalHeat', payload)
			state.animalHeat = payload
		},
		setBloodPressure(state, payload) {
			uni.setStorageSync('bloodPressure', payload)
			state.bloodPressure = payload
		},
		setSphygmus(state, payload) {
			uni.setStorageSync('sphygmus', payload)
			state.sphygmus = payload
		},
		setBreathe(state, payload) {
			uni.setStorageSync('breathe', payload)
			state.breathe = payload
		},
		setMyAddress(state, payload) {
			uni.setStorageSync('myaddress', payload)
			state.myaddress = payload
		},
		setHospitalAddress(state, payload) {
			uni.setStorageSync('hospitalAddress', payload)
			state.hospitalAddress = payload
		},
		setDetailAddress(state, payload) {
			uni.setStorageSync('detailAddress', payload)
			state.detailAddress = payload
		},
		setSystem(state, payload) {
			uni.setStorageSync('system', payload)
			state.system = payload
		},
		setToken(state, payload) {
			uni.setStorageSync('token', payload)
			state.token = payload
		},
		setUserInfo(state, payload) {
			console.log('store存储用户信息----', payload);
			uni.setStorageSync('userInfo', payload)
			state.userInfo = payload
		},
		setWxUserInfo(state, payload) {
			uni.setStorageSync('wxUserInfo', payload)
			state.wxUserInfo = payload
		},
		setUuid(state, payload) {
			uni.setStorageSync('uuid', payload)
			state.uuid = payload
		},
		setAttestStatus(state, payload) {
			uni.setStorageSync('attestStatus', payload)
			state.attestStatus = payload
		},
		setNameStatus(state, payload) {
			uni.setStorageSync('nameStatus', payload)
			state.nameStatus = payload
		},
		setContactList(state, payload) {
			uni.setStorageSync('contactList', payload)
			state.contactList = payload
		},
		setContactLists(state, payload) {
			uni.setStorageSync('contactLists', payload)
			state.contactLists = payload
		},
		loginOut(state) {
			Object.keys(state).forEach((k) => {
				Vue.delete(state, k)
			})
		},
		getUncompleteOrder(state, payload) {
			uni.setStorageSync('hasUncompleteOrder', payload)
			state.hasUncompleteOrder = payload
		},
		setcurItem(state, payload) {
			uni.setStorageSync('curItem', payload)
			state.curItem = payload
		},
		myInviteObj(state, payload) {
			uni.setStorageSync('myInviteObj', payload)
			state.myInviteObj = payload
		},
		setTimer(state, payload) {
			uni.setStorageSync('timer', payload)
			state.timer = payload
		},
		setIsRecord(state, payload) {
			uni.setStorageSync('isRecord', payload)
			state.isRecord = payload
		},
		clearTimer(state, payload) {
			if (state.timer) {
				clearInterval(state.timer)
				uni.removeStorageSync('timer')
			}
		},
		setLaunch(state, payload) {
			if (state.timer) {
				clearInterval(state.launch)
				uni.removeStorageSync('launch')
			}
		},


	},
	actions: {
		// 持续上报位置
		async continuousReportLocation({
			state,
			commit,
			dispatch
		}, payload) {
			console.log("开始")
			let platform = uni.getSystemInfoSync().platform
			let orderNumber = payload.orderNumber
			uni.startLocationUpdate({
				success: (res1) => {
					console.log("成功", res1)
					uni.onLocationChange(async res => {
						console.log('实时位置信息', res)
						// 10s上报一次，判断时间间隔
						const nowTimestamp = +new Date()
						if (!res.latitude) return
						if (nowTimestamp - state.reportInterval * 1000 < state
							.lastReportTimestamp) return
						console.log("时间", nowTimestamp, state
							.lastReportTimestamp)
						// 开始上报
						const params = {
							latitude: res.latitude,
							longitude: res.longitude,
							equipment: platform == 'android' ? 1 : 0,
							orderNumber: orderNumber,
						}
						console.log("参数=======", params)
						nurseAuthorizationLocating(params).then(res => {
							// if(res.success)
							console.log("结果======", res)
							if (res.success) {
								uni.stopLocationUpdate()
							}
							// // #ifdef APP
							// plus.nativeUI.toast(res.success)
							// // #endif
						}).catch((err) => {
							if (err.codeMsg) {
								uni.stopLocationUpdate()
							}
						})


						// 记录最后上报时间
						commit('setState', {
							name: 'lastReportTimestamp',
							value: +new Date()
						})
						console.log("持续上报==============", state.lastReportTimestamp)
						if (process.env.NODE_ENV === 'development') {
							// uni.showModal({
							// 	title: '位置更新提醒',
							// 	showCancel: false,
							// 	content: `上报成功：${JSON.stringify(params)} 时间：${dayjs(
							//     new Date()
							//   ).format('YYYY[年]MM[月]DD[日] HH:mm:ss ')},上次上报时间：${dayjs(state.lastReportTimestamp).format('YYYY[年]MM[月]DD[日]  HH:mm:ss ')}`,
							// 	success: (res) => {
							// 		if (res.confirm) {
							// 			// uni.stopLocationUpdate()
							// 		}
							// 	},
							// 	fail: (err) => {
							// 		console.log("err", err)
							// 	}
							// })
						}
						


					})
				},
				fail: err => {
					console.log("fail", err)
					// if (err.errMsg.includes('auth deny')) {
					//   uni.showModal({
					//     title: '重要提醒',
					//     content: '需要开启位置权限，以便正常使用小程序，请选择使用小程序期间和离开小程序后',
					//     showCancel: false,
					//     success: () => {
					//       uni.openSetting({
					//         success: () => console.log('打开成功')
					//       })
					//     }
					//   })
					// }
				}
			})
		},
		// 存储用户基本信息
		async getUserInfo({
			commit,
			dispatch,
			state
		}, payload) {
			uni.setStorageSync('userInfo', '')
			await delay(300)
			commit('setNurseid', payload.id);
			let res = await getLoginInfo({
				nurseId: payload.id
			})

			if (res.success) {

				dispatch('loginLog', res)
				console.log(res, '用户个人信息是')
				await dispatch('selectNurseInviteRemind')
				commit('setUserInfo', res.object)

				let attestStatus = res.object.attestStatus == 2 ? true : false
				commit('setAttestStatus', attestStatus)

				let nameStatus = res.object.nameStatus == 2 ? true : false
				commit('setNameStatus', nameStatus)
				commit('disableToLogin', res.object.status)
				uni.setStorageSync('isLogin', true)
				// ??????????
				// uni.setStorageSync('address','')
				if (uni.getStorageSync('token')) {
					uni.setStorageSync('yaoqing', false)
					uni.switchTab({
						url: '/pages/tabbars/index/index'
					})
				}
			}
			//  let res1=await selectAllUrgencyLinkman()
			//  if(res1.success){
			// 	let contactList=res1.object.length==0?false:true
			// 	commit('setContactLists',contactList)
			// }
		},
		async loginLog({
			state
		}, payload) {
			// -----还有经纬度
			let obj = {
				loginType: 'APP登录',
				mobile: payload.object.mobile
			}
			if (state.latitude) {
				obj.latitude = state.latitude
			}
			if (state.longitude) {
				obj.longitude = state.longitude
			}
			loginLog({
				...obj
			})
		},
		// 一键登录
		async userOneKeyLogin({
			commit,
			state,
			dispatch
		}, payload) {
			// console.log(state.system.brand,'手机品牌');
			let obj = {}
			if (state.cid) {
				obj.cid = state.cid
			}
			obj.mobile = payload
			console.log(obj, '===============')
			let res = await oneKeyLoginUnipush(obj)
			commit('setToken', res.object.token)
			console.log(res, '一键登录信息是-----');
			dispatch('getUserInfo', {
				token: res.object.token,
				id: res.object.nurseId
			})
			// uni.setStorageSync("isLogin", true); //赋值

		},
		// 是否可以预登陆判断
		preLogin() {
			return new Promise((resolve, reject) => {
				// #ifdef H5
				resolve(false)
				// #endif
				// #ifdef APP
				uni.preLogin({
					provider: 'univerify',
					success: (res) => {
						resolve(true)
					},
					fail: (err) => {
						console.log("preLogin fail: ", err);
						resolve(false)
					}
				})
				// #endif

			})
		},
		login({
			dispatch
		}) {
			uni.showModal({
				title: '温馨提示',
				content: '登录过期，请您重新登录。',
				confirmColor: '#3C8EFF',
				success: async (res) => {
					if (res.confirm) {
						let res = await dispatch('preLogin')
						if (res) {
							uni.reLaunch({
								url: '../../login-register/one-key-login/one-key-login'
							})
						} else {
							uni.reLaunch({
								url: '../../login-register/login/login'
							})
						}

					}
				}
			})
		},
		// 是否登录
		isLogin({
			commit,
			state
		}, payload) {
			return new Promise((resolve, reject) => {
				if (!state.userInfo.id) {
					resolve(true)
				} else {
					resolve(false)
					uni.showModal({
						title: '温馨提示',
						content: '你还未登录，请点击去登录。',
						confirmColor: '#3C8EFF',
						confirmText: '去登录',
						success(res) {
							if (res.confirm) {
								uni.navigateTo({
									url: '../../login-register/login/login'
								})
							}
						}
					})
				}
			})
		},
		// 查询登录护士是否默认弹窗
		async selectNurseInviteRemind({
			commit,
			state
		}, payload) {
			let res = await selectNurseInviteRemind()
			if (res.success && (res.object == 1)) {
				commit('setShowInvite', true)
			}

		},
		// 护士更新地址
		updateAddress({
			commit,
			state
		}, payload) {
			//护士详细地址
			if (state.userInfo && state.userInfo.id) {
				commit('setDetailAddress', payload)
				let nurseId = state.userInfo.id
				// 更新
				authentication({
					address: payload,
					nurseId: nurseId
				}).then(r => {
					console.log('地址更新=========pppppp', res)
				})
			}


		},
		// 是否实名认证、资格认证--完成可接单
		goLogin() {
			uni.redirectTo({
				url: '../../login-register/login/login'
			})
		},
		//拨打电话
		call() {
			uni.makePhoneCall({
				phoneNumber: '4008809120',
			})
		},
		// 是否有网络
		isNetWork() {
			// document.addEventListener("netchange", function(){
			// 	//网络状态变化
			// }, false);
			let flag = false
			return new Promise((resolve, reject) => {
				// 获取当前网络状态
				uni.getNetworkType({
					success: function(res) {
						// console.log(res);
						if (res.networkType == 'none') {
							flag = false
							plus.nativeUI.toast('服务器网络异常，请稍后重试')
							// uni.showToast({
							// 	title:'服务器网络异常，请稍后重试',
							// 	icon:'none'
							// })
							resolve(flag)
						} else {
							flag = true
							resolve(flag)
						}
					}
				});
			})
		},
	},
	modules: {


	}
})

store.setState = (namespace, name, value) => store.commit(`${namespace}/setState`, {
	name,
	value
})

// 使用方法 this.$store.setState(模块名，属性名，属性值) 。 可快速改变vuex中的状态，如果该属性在saveStateKeys有存储，则同时会改变缓存中该值

export default store